//axios公共工具函数
//1.引入axios
import axios from 'axios'
//引入store仓库
import store from '@/store'

//引入message消息提示
import { Message } from 'element-ui'

//封装公共地址
//封装超时时间
const instance = axios.create({
    baseURL: 'http://sell.h5.itsource.cn:8087', //公共地址
    timeout: 10000, //超时时间10s
})

//封装请求拦截器  可以携带统一参数
instance.interceptors.request.use(
    //config  请求信息对象
    config => {
        //console.log('store.getters.token :>> ', store.getters.token)
        //1.获取token
        const token = store.getters.token

        //2.token挂载在config.headers的某个字段(authorization)和后端商议
        config.headers.authorization = token
        return config
    },
    //抛出错误信息
    err => {
        return Promise.reject(err)
    }
)

//封装相应拦截器    处理状态码
instance.interceptors.response.use(
    response => {
        //response  响应信息对象

        //处理成功状态码：200/201就不全局用了,给用户体验感变差
        let { code, msg } = response.data
        if (code === 0) {
            Message.success(msg)
        }
        if (code === 1) {
            Message.error(msg)
        }

        if (code === 5001) {
            Message.error(msg)
        }
        return response
    },
    //抛出错误信息
    err => {
        //处理失败状态码
        // console.log('err :>> ', err);
        //err.message
        //err.response.status 404
        //err.response.status 401
        let { message, response } = err
        if (response) {
            switch (response.status) {
                case 401:
                    Message.error(message)
                    break
                case 403:
                    Message.error(message)
                    break
                case 404:
                    Message.error(message)
                    break
                case 500:
                    Message.error(message)
                    break
                default:
                    Message.error(message)
                    break
            }
        } else {
            Message.error(message)
        }
        return Promise.reject(err)
    }
)

//导出封装好的axios
export default instance